import * as express from "express";
import * as http from "http";
import * as ws from "ws";
import { SignalMessage } from "./type";
import * as wshandler from "./class/websockethandler";
import { generateRandomString } from "../utils/idGenerator";
export class WebSocketServer {
    private app: express.Application;
    private server: http.Server;
    private ws :  ws.WebSocketServer;

    constructor(app: express.Application) {
        this.app = app;
        this.server = http.createServer(this.app);
        this.ws = new ws.WebSocketServer({server: this.server});
    }

    public start(port: number) {
        this.server.listen(port,'0.0.0.0', () => {
            console.log(`WebSocket server started on port ${port}`);
        });

        this.ws.on("connection",(ws:ws.WebSocket)=>{
            const clientId = generateRandomString(5);
            console.log("New connection:",clientId);
            
            ws.on("message",(data:string)=>{
                const msg:SignalMessage = JSON.parse(data);
                this.handleMessage(ws, msg,clientId);
                console.log("Received Message:",msg);
            }),

            ws.on("leave",(a)=>{
                console.log("leave:",a);
            })
        })
    }

    private handleMessage(ws: ws.WebSocket, message: SignalMessage, clientId:string): void {
        switch (message.type) {
          case "join":
            console.log(`Registered ${clientId}`);
            message.roomId ?
              wshandler.joinRoom(message.roomId,clientId,ws):
              wshandler.createRoom(ws,clientId);
            break;
          case "leave":
            console.log(`Unregistered`);
            break;
          case "offer":
                wshandler.onOffer(message.roomId,message);
                break;
          case "answer":
                wshandler.onAnswer(message.roomId,message);
                break;
          case "candidate":
                wshandler.onCandidate(message.roomId,message);
                break;
          default:
            console.log(`Unknown message type: ${message.type}`);
        }
    }

}